﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Misc;
using JiveMessenger.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;

namespace JiveMessenger.ViewModels
{
    public class ViewModelApplicationUpdate : ViewModelBase, IViewModelApplicationUpdate
    {
        private IClient _currentClient;

        public RelayCommand DownloadUpdateCommand { get; set; }

        private Updater _availableUpdate;
        public Updater AvailableUpdate
        {
            get { return _availableUpdate; }
            set
            {
                if (_availableUpdate != value)
                {
                    Set(() => AvailableUpdate, ref _availableUpdate, value);
                }
            }
        }

        public ViewModelApplicationUpdate(IClient currentClient)
        {
            this.DownloadUpdateCommand = new RelayCommand(DownloadUpdateCommandAction);
            Messenger.Default.Register<NotificationMessage<Updater>>(this, msg =>
                {
                    switch (msg.Notification)
                    {
                        case "NewApplicationVersionFound":
                            this.AvailableUpdate = msg.Content;
                            break;
                    }
                });
            Messenger.Default.Register<NotificationMessageAction<Updater>>(this, msg =>
                {
                    switch (msg.Notification)
                    {
                        case "GetAvailableUpdate":
                            msg.Execute(AvailableUpdate);
                            break;
                    }
                });
            _currentClient = currentClient;
        }

        private void DownloadUpdateCommandAction()
        {
            Messenger.Default.Send(new NotificationMessageAction<MessageBoxResult>(this, string.Format("A new version of Jive Messenger is available. Your current version is {0}, and the new version is {1}. Do you wish to update?", Assembly.GetExecutingAssembly().GetName().Version.ToString(), this.AvailableUpdate.VersionNumber), "QueryDownloadUpdate", result =>
                {
                    if (result == MessageBoxResult.OK || result == MessageBoxResult.Yes)
                        _currentClient.DownloadApplicationUpdate(AvailableUpdate.DownloadUrl);
                }));
        }
    }
}
